package com.flag.liutao.common.utils;

import com.flag.liutao.common.handler.MyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Component
public class MyImgUtil {

    @Value("${upload.path}")
    private  String path;

    public  String upload (MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        if(!originalFilename.endsWith(".jpg")&&!originalFilename.endsWith(".jpeg")&&!originalFilename.endsWith(".png")){
            throw new MyException("请上传图片文件");
        }

        String end = originalFilename.substring(originalFilename.indexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
        String format = sdf.format(new Date());
        String newName = UUID.randomUUID().toString()+end;
        String realPath = path + format;
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String fileName = realPath + "/" + newName;
        try {
            file.transferTo(new File(folder,newName));
        } catch (IOException e) {
            e.printStackTrace();
            throw   new MyException("文件上传失败");
        }
        return format +"/"+  newName;
    }
}
